class Dashboard {
    constructor() {
        this.charts = {};
        this.currentTimeRange = 'month'; // 默认显示月数据
        this.initCharts();
        this.setupEventListeners();
        this.startDataRefresh();
    }

    initCharts() {
        // 初始化生长趋势图表
        this.charts.growth = echarts.init(document.getElementById('growthTrendChart'));
        // 初始化时就调用一次更新
        this.updateGrowthChart(this.currentTimeRange);

        // 初始化灾情分布图表
        const disasterChart = echarts.init(document.getElementById('disasterDistributionChart'));
        const disasterOption = {
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    type: 'pie',
                    radius: '50%',
                    data: [
                        { value: 40, name: '干旱' },
                        { value: 25, name: '病虫害' },
                        { value: 20, name: '涝灾' },
                        { value: 15, name: '其他' }
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        disasterChart.setOption(disasterOption);
        this.charts.disaster = disasterChart;
    }

    setupEventListeners() {
        // 处理时间范围切换
        const chartCard = document.querySelector('.chart-card');
        if (chartCard) {
            const timeButtons = chartCard.querySelectorAll('.card-actions .btn-action');
            timeButtons.forEach(btn => {
                btn.addEventListener('click', (e) => {
                    // 移除所有按钮的active类
                    timeButtons.forEach(b => b.classList.remove('active'));
                    // 给当前点击的按钮添加active类
                    e.target.classList.add('active');
                    
                    // 获取时间范围并更新图表
                    const timeRange = e.target.getAttribute('data-range') || e.target.textContent.toLowerCase();
                    console.log('Button clicked:', timeRange);
                    this.updateGrowthChart(timeRange);
                });
            });
        } else {
            console.error('Chart card not found');
        }

        // 处理预警处理按钮
        document.querySelectorAll('.btn-handle').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const alertItem = e.target.closest('.alert-item');
                alertItem.style.opacity = '0.5';
                btn.textContent = '已处理';
                btn.disabled = true;
            });
        });

        // 处理监控点查看按钮
        document.querySelectorAll('.btn-view').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const monitorName = e.target.closest('.monitor-item').querySelector('.name').textContent;
                this.viewMonitorDetail(monitorName);
            });
        });
    }

    updateGrowthChart(timeRange) {
        console.log('Updating chart for:', timeRange);
        
        // 确保timeRange是有效值
        if (!['week', 'month', 'year'].includes(timeRange)) {
            console.error('Invalid time range:', timeRange);
            return;
        }

        const chartData = {
            week: {
                xData: ['6月1日', '6月2日', '6月3日', '6月4日', '6月5日', '6月6日', '6月7日'],
                series: {
                    rice: [0.65, 0.67, 0.69, 0.68, 0.70, 0.71, 0.72],
                    wheat: [0.58, 0.60, 0.61, 0.60, 0.62, 0.63, 0.64],
                    corn: [0.52, 0.53, 0.54, 0.54, 0.55, 0.56, 0.57]
                }
            },
            month: {
                xData: ['6月1日', '6月5日', '6月10日', '6月15日', '6月20日', '6月25日', '6月30日'],
                series: {
                    rice: [0.65, 0.68, 0.72, 0.75, 0.78, 0.81, 0.83],
                    wheat: [0.58, 0.61, 0.65, 0.68, 0.71, 0.73, 0.75],
                    corn: [0.52, 0.55, 0.59, 0.62, 0.65, 0.67, 0.69]
                }
            },
            year: {
                xData: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                series: {
                    // 水稻生长周期：4月播种，8月收获
                    rice: [0, 0, 0, 0.3, 0.45, 0.65, 0.78, 0.85, 0.75, 0.4, 0, 0],
                    // 小麦生长周期：10月播种，次年6月收获
                    wheat: [0.35, 0.38, 0.45, 0.58, 0.72, 0.85, 0.45, 0, 0, 0.3, 0.32, 0.33],
                    // 玉米生长周期：6月播种，9月收获
                    corn: [0, 0, 0, 0, 0, 0.35, 0.55, 0.75, 0.82, 0.45, 0, 0]
                }
            }
        };

        const data = chartData[timeRange];
        const option = {
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    let result = params[0].axisValue + '<br/>';
                    params.forEach(param => {
                        result += `${param.seriesName}: ${(param.value).toFixed(2)}<br/>`;
                    });
                    return result;
                }
            },
            legend: {
                data: ['水稻', '小麦', '玉米'],
                right: '5%'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: data.xData,
                axisLine: {
                    lineStyle: {
                        color: '#ddd'
                    }
                }
            },
            yAxis: {
                type: 'value',
                name: 'NDVI指数',
                min: 0,
                max: 1,
                interval: 0.2,
                splitLine: {
                    lineStyle: {
                        color: '#eee'
                    }
                }
            },
            series: [
                {
                    name: '水稻',
                    type: 'line',
                    smooth: true,
                    data: data.series.rice,
                    itemStyle: { color: '#27ae60' },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(39, 174, 96, 0.3)' },
                            { offset: 1, color: 'rgba(39, 174, 96, 0.1)' }
                        ])
                    }
                },
                {
                    name: '小麦',
                    type: 'line',
                    smooth: true,
                    data: data.series.wheat,
                    itemStyle: { color: '#f1c40f' },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(241, 196, 15, 0.3)' },
                            { offset: 1, color: 'rgba(241, 196, 15, 0.1)' }
                        ])
                    }
                },
                {
                    name: '玉米',
                    type: 'line',
                    smooth: true,
                    data: data.series.corn,
                    itemStyle: { color: '#e67e22' },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(230, 126, 34, 0.3)' },
                            { offset: 1, color: 'rgba(230, 126, 34, 0.1)' }
                        ])
                    }
                }
            ]
        };

        // 确保图表实例存在并更新
        if (!this.charts.growth) {
            this.charts.growth = echarts.init(document.getElementById('growthTrendChart'));
        }

        try {
            this.charts.growth.setOption(option, true);
            console.log('Chart updated successfully');
        } catch (error) {
            console.error('Error updating chart:', error);
        }
    }

    async updateChartData(timeRange) {
        try {
            const data = await this.fetchData(timeRange);
            this.updateCharts(data);
        } catch (error) {
            console.error('更新图表数据失败:', error);
        }
    }

    startDataRefresh() {
        // 定时刷新数据
        setInterval(() => {
            this.refreshData();
        }, 60000); // 每分钟刷新一次
    }

    async refreshData() {
        try {
            const data = await this.fetchData();
            this.updateDashboard(data);
        } catch (error) {
            console.error('刷新数据失败:', error);
        }
    }

    viewMonitorDetail(monitorName) {
        // 跳转到视频监控页面并定位到特定监控点
        window.location.href = `video.html?monitor=${encodeURIComponent(monitorName)}`;
    }
}

// 初始化仪表盘
document.addEventListener('DOMContentLoaded', () => {
    const dashboard = new Dashboard();
    // 确保默认显示月数据
    dashboard.updateGrowthChart('month');
}); 